package com.iemp.web.controller.file.transfer;


import com.iemp.config.consts.ApiConsts;
import com.iemp.config.consts.EntityConsts;
import com.iemp.my.CustomString;
import com.iemp.my.FileResource;
import com.iemp.util.CustomFilenameUtils;
import com.iemp.util.IPUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

@CrossOrigin
@RestController
@RequestMapping(EntityConsts.FILE_TRANSFER)
@PropertySource("classpath:fileTransferSettings.properties")
public class FileTransferController {

    @Value("${server.port}")
    private final String port = null;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${transfer.upload.folder}")
    private final String uploadFloder = null;

    @Value("${transfer.download.prefix}")
    private String downloadPrefix = null;

    private String getDownloadPathPrefix() {
        return  (downloadPrefix + ":" + port + "/api/" + EntityConsts.FILE_TRANSFER + ApiConsts.DOWNLOAD)
                .replace("{fileName}", "");
    }

    @PostMapping(ApiConsts.UPLOAD)
    public CustomString upload(@RequestParam("src") MultipartFile src) throws IOException {

        String originalFilename = src.getOriginalFilename();
        String formatedFileName = CustomFilenameUtils.formatFilenameTimeStamp(originalFilename);
        log.info("formated fileName:{}", formatedFileName);

        File dst = new File(uploadFloder, formatedFileName);

        dst.createNewFile();
        src.transferTo(dst);

        /* URL 拼接 */
        if ("AUTO".equals(downloadPrefix)) {
            downloadPrefix = ("http://" + IPUtils.ipv4() + ":" + port).replace("\n", "");
        } else {
//            downloadPrefix = downloadPrefix + ":" + port;
        }

        String downloadPath =
                getDownloadPathPrefix() + formatedFileName;

        return new CustomString(downloadPath);
    }

    @GetMapping(ApiConsts.LIST_FILES)
    public Collection<FileResource> listFiles() {
        File dir = new File(uploadFloder);
        File[] files = dir.listFiles();
        Collection<FileResource> fileResouces = new ArrayList<>();
        String downloadPathPrefix = getDownloadPathPrefix();
        Arrays.stream(files).forEach(file -> {
            fileResouces.add(new FileResource(file, downloadPathPrefix));
        });
        return fileResouces;
    }


    @GetMapping(ApiConsts.DOWNLOAD)
    public ResponseEntity<Resource> download(@PathVariable String fileName) {

        File src = new File(uploadFloder, fileName);

        String contentDisposition = ContentDisposition
                .builder("attchment")
                .filename(fileName)
                .build().toString();

        ResponseEntity<Resource> resourceResponseEntity = ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .body(new FileSystemResource(src));

        return resourceResponseEntity;
    }

}
